﻿using Developer.Core.FrameWork.DynamicMiddlePlatformService.Extensions;
using Developer.Core.FrameWork.DynamicMiddlePlatformService.Impl;
using Developer.Core.FrameWork.DynamicMiddlePlatformService.Service;
using Developer.Core.FrameWork.MicroClients.Options;
using Developer.Core.FrameWork.MicroClients.Proxy;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Text;

namespace Developer.Core.FrameWork.MicroClients.Extensions
{
    /// <summary>
    /// 微服务客户端代理扩展类
    /// </summary>
    public static class MicroClientServiceCollectionExtensions
    {
        /// <summary>
        /// 添加中台
        /// </summary>
        /// <param name="services"></param>
        /// <param name="assemblyName"></param>
        /// <returns></returns>
        public static IServiceCollection AddMicroClient(this IServiceCollection services,string assemblyName)
        {
            // 1、注册动态中台
            services.AddDynamicMiddlePlatform<IDynamicMiddlePlatformService, DefaultDynamicMiddlePlatformService>();

            // 2、注册微服务代理客户端工厂
            services.AddSingleton<MicroClientProxyFactory>();

            // 3、注册微服务代理客户端
            services.AddSingleton<MicroClientList>();

            // 4、注册MicroClient代理对象
            ServiceProvider serviceProvider = services.BuildServiceProvider();
            MicroClientList microClient = serviceProvider.GetRequiredService<MicroClientList>();

            IDictionary<Type, object> dics = microClient.GetClients(assemblyName);
            foreach (var key in dics.Keys)
            {
                services.AddSingleton(key, dics[key]);
            }

            return services;
        }

        /// <summary>
        /// 添加中台
        /// </summary>
        /// <param name="services"></param>
        /// <param name="options"></param>
        /// <returns></returns>
        public static IServiceCollection AddMicroClient(this IServiceCollection services,Action<MicroClientOptions> options)
        {
            MicroClientOptions microClientOptions = new MicroClientOptions();
            options(microClientOptions);

            // 1、注册动态中台
            services.AddDynamicMiddlePlatform<IDynamicMiddlePlatformService, DefaultDynamicMiddlePlatformService>(microClientOptions.dynamicMiddlePlatformOptions);

            // 2、注册代理客户端工厂
            services.AddSingleton<MicroClientProxyFactory>();

            // 3、注册代理客户端集合
            services.AddSingleton<MicroClientList>();

            // 4、注册代理对象
            ServiceProvider serviceProvider = services.BuildServiceProvider();
            MicroClientList microClientList = serviceProvider.GetRequiredService<MicroClientList>();

            IDictionary<Type, object> dics = microClientList.GetClients(microClientOptions.AssemblyName);
            foreach (var key in dics.Keys)
            {
                services.AddSingleton(key, dics[key]);
            }

            return services;
        }
    }
}
